#include "stdafx.h"

int waveWriteIn(
			audio_data_t* pAudio,
			const void* pBuffer,
			unsigned int frames
			)
{
	return snd_pcm_writei(pAudio->pHandle, pBuffer, frames);
}

int waveInit(
			audio_data_t* pAudio
			)
{
	/* initialize alsa */
	int rc;
	int dir;
	snd_pcm_hw_params_t *params;
	unsigned int val;
	snd_pcm_uframes_t frames;

	/* Open PCM device for playback. */
	rc = snd_pcm_open(&(pAudio->pHandle), "default", SND_PCM_STREAM_PLAYBACK, 0);
	if (rc < 0)
	{
		fprintf(stderr, "unable to open pcm device: %s\n", snd_strerror(rc));
		return rc;
	}

	/* Allocate a hardware parameters object. */
	snd_pcm_hw_params_alloca(&params);

	/* Fill it in with default values. */
	snd_pcm_hw_params_any(pAudio->pHandle, params);

	/* Set the desired hardware parameters. */

	/* Interleaved mode */
	snd_pcm_hw_params_set_access(pAudio->pHandle, params, SND_PCM_ACCESS_RW_INTERLEAVED);

	/* Signed 16-bit little-endian format */
	snd_pcm_hw_params_set_format(pAudio->pHandle, params, SND_PCM_FORMAT_S16_LE);

	/* Two channels (stereo) */
	snd_pcm_hw_params_set_channels(pAudio->pHandle, params, 2);

	/* 44100 bits/second sampling rate (CD quality) */
	val = 44100;
	snd_pcm_hw_params_set_rate_near(pAudio->pHandle, params, &val, &dir);

	/* Set period size to MAD frames. */
	frames = 1152;
	snd_pcm_hw_params_set_period_size_near(pAudio->pHandle, params, &frames, &dir);

	/* Write the parameters to the driver */
	rc = snd_pcm_hw_params(pAudio->pHandle, params);
	if (rc < 0) 
	{
		fprintf(stderr, "unable to set hw parameters: %s\n", snd_strerror(rc));
		return rc;
	}

	return 0;
}

void waveReset(
			audio_data_t* pAudio
			   )
{
	snd_pcm_drain(pAudio);
	snd_pcm_prepare(pAudio);
}

void waveClose(
			audio_data_t* pAudio
			)
{
	/* free audio */
	snd_pcm_drain(pAudio->pHandle);
	snd_pcm_close(pAudio->pHandle);	
}
